package com.yj.rabbitClient.ack;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.yj.rabbitClient.util.RabbitMQUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息发送方
 */
public class Publisher {

    /*
        消息确认机制：
        消息确认机制描述了一种消息是否已经被发送到 RabbitMQ Server 中以及 RabbitMQ Server 与生产端之间的关系。
     */
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtil.getConnection();

        Channel channel = connection.createChannel();

        String queueName = "helloworld";
        channel.queueDeclare(queueName,false,false,false,null);
        channel.confirmSelect();//开启等待确认
        channel.basicPublish("",queueName,null,"hello world".getBytes());

        try {
            channel.addConfirmListener(new ConfirmListener() {
                @Override
                public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                    System.out.println("消息MQ Broker签收");
                    System.out.println(deliveryTag);
                    System.out.println(multiple);
                }

                @Override
                public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                    System.out.println("消息没有被MQ Broker签收");
                    System.out.println(deliveryTag);
                    System.out.println(multiple);
                }

            });
            Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                channel.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
